<?php

//define('SEARCH_STRING_KEY', 'location_cck_widgets_search_string');

function _suggest_json($type_name, $field_name, $string = '') {
  module_load_include('inc', 'autocomplete_widgets', 'autocomplete_widgets.common');
  $field = content_fields($field_name, $type_name);
  $match = 'contains';

  //Temporarilly forge widget type to trigger neccessary logic inside autocomplete_widgets
  $original_widget_type = $field['widget']['type'];
  $field['widget']['type'] = 'autocomplete_widgets_allowvals';

  //inject $string, otherwise unavailable inside _allowed_values
  $field[SEARCH_STRING_KEY] = $string;
  $options = location_cck_allowed_values($field);
  //Clean things up as if nothing ever happened..
  unset($field[SEARCH_STRING_KEY]);
  $field['widget']['type'] = $original_widget_type;

  $matches = array();
  foreach ($options as $key => $value) {
    $value = array_map('check_plain', $value);
    // Add a class wrapper for a few required CSS overrides.
    // TODO employ microsoformats
    $matches[$key] = <<<HTML
<div class="reference-autocomplete adr">
 <strong>$value[name]</strong> <span class='weight'>$value[weight]</span>
 <div><small><em>$value[street]</em> <b>$value[city]</b>
 </small></div>
</div>
HTML;
  }
  drupal_json($matches);
}

/**
 * Callback for autocomplete_widgets.module
 * @global <type> $user
 * @param CCK $field object
 * @return An array of lid => name items matching a given context
 */
function location_cck_allowed_values($field){
  $select = 'l.lid, l.name, l.street, l.city';
  $query = <<<SQL
SELECT
  $select,
  COUNT(n.*) AS weight
FROM
  {node} n
INNER JOIN {location_instance} i
  ON CAST(SUBSTRING(i.genid FROM %d) AS INTEGER) = n.nid
INNER JOIN {location} l
  ON l.lid = i.lid
WHERE
  n.type = '%s'
  AND n.uid = %d
  AND i.genid LIKE 'cck:%s:%%'
  AND LOWER(l.name) LIKE '%s%%'
GROUP BY
  $select
ORDER BY
  name,
  weight DESC
SQL;
  global $user;
  $locations = array();

  $result = db_query(
    $query,
    strlen("cck:$field[field_name]: "),//pointer to nid within genid
    $field['type_name'],
    $user->uid,
    $field['field_name'],
    strtolower($field[SEARCH_STRING_KEY])//force case-insesitive search
  );

  while($res = db_fetch_object($result)) {
    $locations[$res->lid] = (array)$res;
  }

  return $locations;
}

function _location_json($lid) {
  return drupal_json(location_load_location($lid));
}